#--------------------------------------------------------------------------------------------------------------------#
#----------------------------------------------- Portmann & Stojanovic ----------------------------------------------#
#--------------------------------------------------- November 2020 --------------------------------------------------#
#------- Are Immigrant-Origin Candidates Penalized in Virtue of Ingroup Favoritism or Outrgoup Hostility? -----------#
#--------------------------------------------------------------------------------------------------------------------#
#----------------- D1 Analysis of questionnaire upon candidates regarding migration background ----------------------#
#--------------------------------------------------------------------------------------------------------------------#

rm(list=ls())
setwd(".../...")
d_survey_mb <- read.csv("Umfrage_SNF-Forschungsprojekt_Universit�t_Luzern_total_r.csv", sep=";")
d_coding_mb <- read.csv("tabelle_zusatzanalyse_migrationshintergrund_r.csv", sep=";")

#------------------------------------------------ Data preparation 

#-------- Combine data

d <- merge(x=d_survey_mb, y=d_coding_mb , by.x=c("name", "f_name"), by.y=c("bfsname", "bfsfname"))

#------- Drop if among main variables NA

d <- d %>% filter(!is.na(nat_d) & !is.na(born_ch_d) & !is.na(moth_born_ch_d) & !is.na(fath_born_ch_d))

#------- Prepare variables

d$Name <- factor(d$nonswissname,
levels = c(0,1), 
labels = c("Swiss", "Non-Swiss"))

#---------------------------------------------- Table 17 Appendix: Candidates with a migration background and with roots abroad, results from candidate survey

d$mb_cat <- NA
d$mb_cat <- ifelse(d$nat_d == 1 & (d$born_ch_d == 2  | d$moth_born_ch_d == 2 | d$fath_born_ch_d == 2) |
(d$nat_d == 2 & (d$moth_born_ch_d == 2 & d$fath_born_ch_d == 2)), 1, 
ifelse(d$nat_d == 1, 2, 
ifelse(d$born_ch_d == 2 | d$moth_born_ch_d==2 | d$fath_born_ch_d==2, 3, 4)))
table(d$mb_cat)

d$mb_cat <- factor(d$mb_cat, 
levels = c(1, 2, 3, 4), 
labels = c("With migration background", "Without migration background, naturalized", 
"Without migration background, him/her or one parent born abroad", 
"Without migration background, no close origins abroad"))

d_t1 <- d %>% 
dplyr::select(Name, mb_cat) %>% 
dplyr::count(Name, mb_cat) %>%
dplyr::group_by(Name) %>%
dplyr::mutate(prop = prop.table(n))

d_t1$prop <- round(d_t1$prop, digits = 2)

t1 <- xtable((as.matrix(d_t1)), caption = "Non-Swiss name vs. Migration background")
names(t1) <- c("Name", "Migration_Background", "n", "Share")
print(t1, include.rownames=FALSE)

